from flask import session
from flask_restful import Resource

from database import Database


class getUserOrders(Resource):
    def get(self):
        db = Database()
        user_id = session.get('username')
        if user_id is None:
            return {'message': 'You are not logged in!'}, 401
        else:
            orders = db.execute_query("select * from orderids where userId = %s", (user_id,))

            if orders is not None:
                orders_formatted = []
                for order in orders:
                    bookIds = db.execute_query("select bookId from linebook where orderId = %s", (order[0],))

                    listBooks = []
                    for bookId in bookIds:
                        book = db.execute_query("select * from book where bookId = %s", (bookId,))

                        book = {
                            "bookId": book[0],
                            "categoryId": book[1],
                            "imageUrl": book[2],
                            "title": book[3],
                            "description": book[4],
                            "quantity": bookId[5]
                        }
                        listBooks.append(book)
                    order = {
                        "orderId": order[0],
                        "userId": order[1],
                        "date": order[2].strftime("%Y-%m-%d %H:%M:%S"),
                        "status": order[3],
                        "quantity": order[4],
                        "class": order[5],
                        "listbooks": listBooks
                    }
                    orders_formatted.append(order)
                return {"orders": orders_formatted}, 200
            else:
                return {"message": "no orders found for this user"}, 404
